package pkg.listener;

import java.util.Collections;
import java.util.TimeZone;
import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheFactory;
import javax.cache.CacheManager;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import pkg.dao.EntityDAO;
import pkg.entity.User;
import pkg.filter.UserFilter;

public class InitServletListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent sce) {
        TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));
        EntityDAO dao = new EntityDAO();
        UserFilter f = new UserFilter();
        f.setEmail("admin");
        User u = (User) dao.findOneByFilter(f);

        if (u == null) {
            u = new User();
            u.setFirstName("System Administrator");
            u.setLastName("Do Not Delete");
            u.setEmail("admin");
            u.setPassword("admin");
            u.setAdmin(Boolean.TRUE);
            dao.update(u);
            System.out.println("Admin user created.");
        }

        Cache cache = null;
        try {
            CacheFactory cf = CacheManager.getInstance().getCacheFactory();
            cache = cf.createCache(Collections.emptyMap());
        } catch (CacheException ex) {
            throw new RuntimeException("Can not create cache.", ex);
        }
        sce.getServletContext().setAttribute("cache", cache);
    }

    public void contextDestroyed(ServletContextEvent sce) {
    }
}
